<?php
/*
 * Copyright 2011 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

  /***********************************\
  *                 *
  * Management of Google Login.  *
  *                 *
  \***********************************/


require_once '../../src/Google_Client.php';
require_once '../../src/contrib/Google_Oauth2Service.php';
require_once '../../../configure.php';
require_once '../../../dao.php';

session_start();

$client = new Google_Client();
$client->setApplicationName(APPLICATION_NAME);
// Visit https://code.google.com/apis/console?api=plus to generate your
// oauth2_client_id, oauth2_client_secret, and to register your oauth2_redirect_uri.
$client->setClientId(CLIENT_ID);
$client->setClientSecret(CLIENT_SECRET);
$client->setRedirectUri(REDIRECT_URI);
$client->setDeveloperKey(DEVELOPER_KEY);
$oauth2 = new Google_Oauth2Service($client);

if (isset($_GET['code'])) {
  $client->authenticate($_GET['code']);
  $_SESSION['token'] = $client->getAccessToken();
  $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
  header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
  return;
}

if (isset($_SESSION['token'])) {
  $client->setAccessToken($_SESSION['token']);
}

if (isset($_REQUEST['logout'])) {
  unset($_SESSION['token']);
  $client->revokeToken();
}

if ($client->getAccessToken()) {
  $user = $oauth2->userinfo->get();

  // These fields are currently filtered through the PHP sanitize filters.
  // See  
  $email = filter_var($user['email'], FILTER_SANITIZE_EMAIL);
  $img = filter_var($user['picture'], FILTER_VALIDATE_URL);
  $personMarkup = "$email<div><img src='$img?sz=50'></div>";

  // The access token may have been updated lazily.
  $_SESSION['token'] = $client->getAccessToken();
} else {
  $authUrl = $client->createAuthUrl();
}
 
 //Get current user's email.
/*
function get_userEmail($token){
  $mail = '';
 
  $url = 'https://www.googleapis.com/oauth2/v1/userinfo';
  $url .= '?access_token='.$token;
 
  $ch = curl_init($url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
  $result_curl = curl_exec($ch);
  $error_curl = curl_error($ch);
  curl_close($ch);
 
  $res = json_decode($result_curl);

  if ($res->email){
    $mail = $res->email;
  }
  return $mail;
}

$jsonTokenUso = json_decode($client->getAccessToken());
  if(!isset($authUrl))
  {
    $mail = get_userEmail($jsonTokenUso->{'access_token'});
    
    if($mail == VERIFICATION_MAIL)
    {
      print "ACCESS GRANTED";                                             //DEPURACIÓN
    }
    else
    {                                                                     //CREAR MÉTODO PARA DESLOGUEAR
      unset($_SESSION['token']);
      $client->revokeToken();
      print "ACCESS DENIED";
      $_SESSION['hola'] = "hola";
      header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
    }
  }
  */
?>
<!doctype html>
<html>
<head><meta charset="utf-8"></head>
<body>
<header><h1>Google UserInfo Sample App</h1></header>
<?php if(isset($personMarkup)): ?>
<?php print $personMarkup ?>
<?php endif ?>
<?php
  if(isset($authUrl)) {
    print "<a class='login' href='$authUrl' target='_self'>Connect Me!</a>"; //Usar Jquery para abrir un popup.
  } else {
   print "<a class='logout' href='?logout'>Logout</a>";
  }
?>
</body></html>